package com.msconfig.utils;

/*
 * author: caojunhao
 * date  : 2020/8/10
 * desc  :
 */

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import com.msconfig.MyApplication;
import com.msconfig.event.SaveDataToFileSuccessEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

public class WriteToFileUtils {
    //把解析好的数据写到文件中
    public static void writeMessageToFile(final String data, final String fileName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String filePath = Environment.getExternalStorageDirectory() + "/" + fileName + ".txt";
                File file = new File(filePath);
                if(!file.exists()){
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                RandomAccessFile raf = null;
                try {
                    raf = new RandomAccessFile(file, "rw");
                    raf.seek(file.length());
                    raf.write((data).getBytes());

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static boolean isExistFile(String fileName){
        String filePath = Environment.getExternalStorageDirectory() + "/" + fileName + ".txt";
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * 删除单个文件
     *
     * @param fileName 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        String filePath = Environment.getExternalStorageDirectory() + "/" + fileName;
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    /**
     * oldPath 和 newPath必须是新旧文件的绝对路径
     */
    public static void renameFile(String oldFileName, String newFileName) {
        if (TextUtils.isEmpty(oldFileName)) {
            return ;
        }

        if (TextUtils.isEmpty(newFileName)) {
            return ;
        }

        String oldFilePath = Environment.getExternalStorageDirectory() + "/" + oldFileName;
        File oldFile = new File(oldFilePath);

        String newFilePath = Environment.getExternalStorageDirectory() + "/" + newFileName;
        File newFile = new File(newFilePath);
        if (!oldFile.isFile() && !oldFile.exists()) {
            return ;
        }

       oldFile.renameTo(newFile);

    }
}
